package com.tpp.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.tpp.comm.pojo.TpOrder;
import com.tpp.pay.config.AliConfig;
import com.tpp.pay.feign.OrderFeign;
import com.tpp.pay.service.PayService;
import org.springframework.boot.autoconfigure.web.format.DateTimeFormatters;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

@Service
public class PayServiceImpl implements PayService {

    @Resource
    private AliConfig aliConfig;

    @Resource
    private OrderFeign orderFeign;

    @Override
    public String pagePay(String orderNo) {
        try {
            TpOrder order = orderFeign.findByOrderNo(orderNo);

            //为alipay提供业务模型数据
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(orderNo);
            model.setSubject(order.getItemName());
            model.setTotalAmount(order.getTotalAmount().toString());
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYY-MM-dd HH:mm:ss");
            model.setTimeExpire(dateTimeFormatter.format(order.getCreatedTime().plusMinutes(5)));
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setBizModel(model);
            request.setReturnUrl(aliConfig.getReturnUrl());
            request.setNotifyUrl(aliConfig.getNotifyUrl());

            //把沙箱提供的数据交给alipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(aliConfig);
            String body = alipayClient.pageExecute(request).getBody();
            return body;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}
